package com.rong.mbt.personal.activity;


import android.app.ProgressDialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.PixelFormat;
import android.hardware.Camera;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.alibaba.android.arouter.launcher.ARouter;
import com.alibaba.fastjson.JSON;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.rong.mbt.personal.R;
import com.rong.mbt.personal.activity.base.PBaseActivity;
import com.rong.mbt.personal.bean.base.BaseBean;
import com.rong.mbt.personal.bean.FaceBean;
import com.rong.mbt.personal.bean.FaceGetImgBean;
import com.rong.mbt.personal.face.CameraPreview;
import com.rong.mbt.personal.face.DetectorProxy;
import com.rong.mbt.personal.face.FaceRectView;
import com.rong.mbt.personal.face.ICameraCheckListener;
import com.rong.mbt.personal.utils.AESDEecode;
import com.rong.mbt.personal.utils.DlgUtil;
import com.rong.mbt.personal.utils.FileUtil;
import com.vise.log.ViseLog;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.util.List;

import io.rong.imkit.RongIM;
import io.rong.imlib.RongIMClient;
import sun.misc.BASE64Encoder;
import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;


public class FaceRecognitionActivity extends PBaseActivity {

    private CameraPreview mFace_detector_preview;
    private FaceRectView mFace_detector_face;
    private Button mFace_detector_take_photo;

    private Context mContext;
    private DetectorProxy mDetectorProxy;


    private ICameraCheckListener mCameraCheckListener = new ICameraCheckListener() {
        @Override
        public void checkPermission(boolean isAllow) {
            if (!isAllow) {
                Toast.makeText(mContext, "权限申请被拒绝，请进入设置打开权限再试！", Toast.LENGTH_SHORT).show();
                finish();
            }
        }

        @Override
        public void checkPixels(long pixels, boolean isSupport) {
            ViseLog.i("checkPixels" + pixels);
            if (!isSupport) {
                Toast.makeText(mContext, "手机相机像素达不到要求！", Toast.LENGTH_SHORT).show();
                finish();
            }
        }
    };
    private String mbtToken;

    private boolean isUploadFace = false; //是否上传过人脸识别图片  false 否  true是
    private ProgressDialog progressDialog;
    private Button tvLogin;
    private SharedPreferences.Editor edit;
    private SharedPreferences sp;
    private String userId;
    private String bitmapBase64Ser;
    private String loginToken;

    @Override
    public int getLayoutId() {
        return R.layout.activity_face_recognition;
    }

    @Override
    public void initView() {
        super.initView();
        mContext = this;
        sp = getSharedPreferences("config", MODE_PRIVATE);
        edit = sp.edit();
        mbtToken = sp.getString("mbtToken", null);
        loginToken = sp.getString("loginToken", null);

        userId = sp.getString("loginid", "");
        Log.i("test", "userId " + userId);
        isUploadFace = getIntent().getBooleanExtra("isGoLogin", false);
        init();

        if (isUploadFace) {
            tvLogin.setVisibility(View.VISIBLE);
        }
        getUserUploadFaceImg();
    }

    protected void init() {
        mFace_detector_preview = (CameraPreview) findViewById(R.id.face_detector_preview);
        mFace_detector_face = (FaceRectView) findViewById(R.id.face_detector_face);
        mFace_detector_face.setZOrderOnTop(true);
        mFace_detector_face.getHolder().setFormat(PixelFormat.TRANSLUCENT);
        mFace_detector_take_photo = (Button) findViewById(R.id.face_detector_take_photo);

        tvLogin = findViewById(R.id.act_fr_tv_login);

        mFace_detector_take_photo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                progressDialog = DlgUtil.showProgressDlg(mContext, "请稍等...");
                progressDialog.show();
                mFace_detector_take_photo.setEnabled(false);
                mFace_detector_preview.getCamera().takePicture(new Camera.ShutterCallback() {
                    @Override
                    public void onShutter() {

                    }
                }, null, new Camera.PictureCallback() {
                    @Override
                    public void onPictureTaken(byte[] bytes, Camera camera) {
                        mFace_detector_preview.getCamera().stopPreview();
                        if (!isUploadFace) {
                            //没有上传过人脸识别
                            FileUtil.saveImage("faceUpload.jpg", bytes);
                            faceUpload(FileUtil.getFile("faceUpload.jpg"));
                        } else {
                            //上传过人脸识别  两个图片的base64 编码做比较
                            Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
                            String newbitmap = encodeImage(bitmap);
                            if (bitmapBase64Ser != null) {
                                comparisonBase64Code(newbitmap, bitmapBase64Ser);
                            } else {
                                Toast.makeText(mContext, "没有上传过图片", Toast.LENGTH_SHORT).show();
                            }
                        }
                    }
                });
            }
        });
        mDetectorProxy = new DetectorProxy.Builder(mFace_detector_preview)
                .setMinCameraPixels(3000000)
                .setCheckListener(mCameraCheckListener)
                .setFaceRectView(mFace_detector_face)
                .setDrawFaceRect(true)
                .build();
        tvLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (sp != null && edit != null) {
                    edit.putBoolean("faceIsOpen", false);
                    edit.commit();
                    ARouter.getInstance().build("/acitvity/login").navigation();
                    finish();
                }
            }
        });
    }

    public void resetinit() {
        if (mDetectorProxy != null) {
            mDetectorProxy.release();
            mDetectorProxy.detector();
            mDetectorProxy.openCamera();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (mDetectorProxy != null) {
            mDetectorProxy.detector();
            mDetectorProxy.setCameraId(Camera.CameraInfo.CAMERA_FACING_FRONT);
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (mDetectorProxy != null) {
            mDetectorProxy.release();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        System.gc();
    }

    //上传人脸识别图片
    public void faceUpload(File file) {
        Luban.with(mContext)
                .load(file)
                .setCompressListener(new OnCompressListener() {
                    @Override
                    public void onStart() {
                    }

                    @Override
                    public void onSuccess(File file) {
                        OkGo.<String>post("http://service.jiangaifen.com:38082/face/insert")
                                .tag(this)
                                .isMultipart(true)
                                .headers("mbtToken", mbtToken)
                                .params("file", file)
                                .execute(new StringCallback() {
                                    @Override
                                    public void onSuccess(Response<String> response) {
                                        if (progressDialog != null) {
                                            progressDialog.cancel();
                                        }
                                        try {
                                            BaseBean baseBean = JSON.parseObject(response.body(), BaseBean.class);
                                            finish();
                                        } catch (Exception e) {
                                        }
                                        mFace_detector_take_photo.setEnabled(true);
                                    }

                                    @Override
                                    public void onError(Response<String> response) {
                                        super.onError(response);
                                        if (progressDialog != null) {
                                            progressDialog.cancel();
                                        }
                                        resetinit();
                                        mFace_detector_take_photo.setEnabled(true);
                                    }
                                });
                    }

                    @Override
                    public void onError(Throwable throwable) {

                    }
                }).launch();
    }

    public String encodeImage(Bitmap bitmap) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 50, baos); //参数如果为100那么就不压缩
        byte[] bytes = baos.toByteArray();
        String encode = new BASE64Encoder().encode(bytes);
        return encode;
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (progressDialog != null) {
                progressDialog.cancel();
            }
            mFace_detector_take_photo.setEnabled(true);
            switch (msg.what) {
                case 10:
                    reconnect(loginToken);
//                    ARouter.getInstance().build("/activity/main").navigation();
//                    finish();
                    break;
                case 11:
                    Toast.makeText(mContext, "匹配失败", Toast.LENGTH_SHORT).show();
                    resetinit();
                    break;
            }
        }
    };

    public void comparisonBase64Code(final String locationBase64, final String serverBase64) {
        final String ak_id1 = "oO5iWjoDuadwgqaY"; //用户ak
        final String ak_secret1 = "C6mcXC3I6cihYVCpY7NIm40VLTKqGP"; // 用户ak_secret
        final String url = "https://dtplus-cn-shanghai.data.aliyuncs.com/face/verify";
        new Thread() {
            @Override
            public void run() {
                super.run();
                try {
                    final String body = "{\"type\": \"1\", \"content_1\":\"" + serverBase64 + "\",\"content_2\":\"" + locationBase64 + "\"}";
                    String s1 = AESDEecode.sendPost(url, body, ak_id1, ak_secret1);
                    FaceBean faceBean = JSON.parseObject(s1, FaceBean.class);
                    if (faceBean.getConfidence() > 80) {
                        handler.sendEmptyMessage(10);
                    } else {
                        handler.sendEmptyMessage(11);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }

    //获取用户上传的face  得到base64 编码
    public void getUserUploadFaceImg() {
        OkGo.<String>post("http://service.jiangaifen.com:38082/face/get")
                .tag(this)
//                .isMultipart(true)
                .headers("mbtToken", mbtToken)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        Log.i("test", "face res " + response.body());
                        final List<FaceGetImgBean> faceList = JSON.parseArray(response.body(), FaceGetImgBean.class);
                        if (!faceList.isEmpty() && !userId.isEmpty()) {
                            for (int i = 0; i < faceList.size(); i++) {
                                if (userId.equals(String.valueOf(faceList.get(i).getUserid()))) {
                                    final String userUploadFaceImg = faceList.get(i).getImageurl();
                                    new Thread() {
                                        @Override
                                        public void run() {
                                            super.run();
                                            try {
                                                final Bitmap bitmap = FileUtil.returnBitmap(userUploadFaceImg);
                                                bitmapBase64Ser = encodeImage(bitmap);
                                            } catch (Exception e) {
                                                e.printStackTrace();
                                            }
                                        }
                                    }.start();
                                }
                            }
                        }
                    }
                });
    }


    private void reconnect(String token) {

        Log.i("test", "reconnect" + token);
        RongIM.connect(token, new RongIMClient.ConnectCallback() {
            @Override
            public void onTokenIncorrect() {
                Toast.makeText(mContext, "融云登录失败", Toast.LENGTH_SHORT).show();
                if (sp != null && edit != null) {
                    edit.putBoolean("faceIsOpen", false);
                    edit.commit();
                    ARouter.getInstance().build("/acitvity/login").navigation();
                    finish();
                }else{
                    ARouter.getInstance().build("/acitvity/login").navigation();
                    finish();
                }
            }

            @Override
            public void onSuccess(String s) {
                ARouter.getInstance().build("/activity/main").navigation();
                finish();
            }

            @Override
            public void onError(RongIMClient.ErrorCode e) {
                Toast.makeText(mContext, "融云登录失败", Toast.LENGTH_SHORT).show();
                if (sp != null && edit != null) {
                    edit.putBoolean("faceIsOpen", false);
                    edit.commit();
                    ARouter.getInstance().build("/acitvity/login").navigation();
                    finish();
                }else{
                    ARouter.getInstance().build("/acitvity/login").navigation();
                    finish();
                }
            }
        });
    }
}